package cn.itcast.store.web.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.store.domain.Category;
import cn.itcast.store.service.CategoryService;
import cn.itcast.store.service.serviceImp.CategoryServiceImp;
import cn.itcast.store.utils.JedisUtils;
import cn.itcast.store.web.base.BaseServlet;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;

/**
 * Servlet implementation class CategoryServlet
 */
public class CategoryServlet extends BaseServlet {
	
	//首页热门商品和最新商品
		public String findAllCats(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException, SQLException {
			response.setContentType("application/json;charset=utf-8");
			
			Jedis j = JedisUtils.getJedis();
			String json = j.get("allCats");
			if (null == json || "".equals(json)) {
				System.out.println("缓存中没有数据");
				// 查询所有分类
				CategoryService CategoryService = new CategoryServiceImp();
				List<Category> list = CategoryService.findAllCats();
				// 将集合中的所有分类信息转换为JSON格式的字符串数据
				System.out.println(list);	
				
				
				JSONArray jsonArray2 = JSONArray.fromObject(list);//将集合转换为json格式
				json =jsonArray2.toString();//将jisn转换为字符串
				
				
				System.out.println(list);
				j.set("allCats", json);
				
			} else {
				System.out.println("缓存中有数据");
				System.out.println();
			}
			
			// 将字符串数据响应到客户端
			response.getWriter().println(json);
			JedisUtils.closeJedis(j);
			return null;
	}
	
	
}
